﻿/// <reference path="canvas.extensions.js" />
/// <reference path="openFileDialog.js" />

var Aquamarine = Aquamarine || {};

Aquamarine.Uploader = function () {

    var self = this;
    var _files = null;

    var _canvas = document.createElement("canvas");
    var _canvasContext = _canvas.getContext("2d");

    var _thumbnailsLoadCount = 0;
    var _thumbnails = [];
    var _images = [];

    self.addEventListener = function (type, listener, useCapture) {
         _canvas.addEventListener(type, listener, useCapture);
    };

    self.dispatchEvent = function (evt) {
        _canvas.dispatchEvent(evt);
    };

    self.getThumbnails = function (files, width, height) {

        _thumbnailsLoadCount = 0;
        _thumbnails.length = 0;

        _canvas.width = width;
        _canvas.height = height;

        for (var i = 0; i < files.length; i++) {
            loadImage(files[i], function (file, image) {
                _canvasContext.drawImage(image, 0, 0, width, height);

                var thumbnail = _canvas.toDataURL("image/jpeg")

                _thumbnails.push({ file: file, base64: thumbnail });

                _thumbnailsLoadCount++;

                var thumbnailEvent = new CustomEvent("thumbnail", { detail: { file: file, base64: thumbnail } });
                self.dispatchEvent(thumbnailEvent);

                if (_thumbnailsLoadCount == files.length) {
                    var allThumbnailEvent = new CustomEvent("allthumbnails", { detail: { images: _thumbnails } });
                    self.dispatchEvent(allThumbnailEvent);
                }
            });
        }
    };

    self.save = function (files, sizes, url) {
        for (var i = 0; i < files.length; i++) {

            loadImage(files[i], function (file, image) {
                var form = new FormData();
                form.append("file1", file, file.name);

                for (var k = 0; k < sizes.length; k++) {
                    _canvas.width = sizes[k].width;
                    _canvas.height = sizes[k].height;
                    _canvasContext.drawImage(image, 0, 0, _canvas.width, _canvas.height);

                    var blob = _canvas.getFile(file.name, "image/jpeg");
                    form.append("file" + (k + 2), blob, file.name);
                }

                var request = new XMLHttpRequest();
                request.open("POST", "http://alvaro.ru.local/file/save");
                request.send(form);
            });
        }
    };

    var loadImage = function (file, postFunc) {
        var reader = new FileReader();

        reader.onload = function (e) {
            var image = new Image();

            image.onload = function () {
                postFunc(file, image);
            };

            image.src = e.currentTarget.result;
        };

        reader.readAsDataURL(file);
    };
};